package com.xuxueli.applyModules.utils;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @CLassName FileUtil
 * @Description 文件操作工具类
 **/
@Slf4j
public class FileUtil {

    public static String filterFilePath(String path) {
        if (path != null) {
            path = path.replace("../", "").replace("..\\", "");
        }
        return path;
    }

    /**
     * 保存文件路径
     * @param path
     * @param name
     * @param in
     */
    public static void saveFile(String path, String name, InputStream in) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        try (BufferedOutputStream out = new BufferedOutputStream(
            new FileOutputStream(new File(path + "/" + name)))) {
            byte[] bytes = new byte[2048];
            int length;
            while ((length = in.read(bytes)) != -1) {
                out.write(bytes, 0, length);
            }
            out.flush();
            in.close();
        } catch (IOException e) {
            log.error("保存文件异常", e);
        }
    }

    /**
     * 下载文件
     * @param path
     * @param name
     * @param out
     */
    public static void downloadFile(String path, String name, OutputStream out) {
        File file = new File(path + File.separator + name);
        if (!file.exists()) {
            log.info("文件不存在,{}", name);
            return;
        }
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) {
            byte[] bytes = new byte[2048];
            int length;
            while ((length = in.read(bytes)) != -1) {
                out.write(bytes, 0, length);
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("下载文件异常", e);
        }
    }

    /**
     * 下载图片
     * @param iconPath
     * @param icon
     * @param response
     */
    public static void downloadIcon(String iconPath, String icon, HttpServletResponse response) {
        File file = new File(iconPath + File.separator + icon);
        if (!file.exists()) {
            log.error("图片logo不存在");
            return;
        }
        try (
                FileInputStream inputStream = new FileInputStream(file); OutputStream outputStream = response
                .getOutputStream()) {
            byte[] data = new byte[(int) file.length()];
            inputStream.read(data);
            if (icon.endsWith("svg")) {
                response.setContentType("image/svg+xml");
            } else {
                response.setContentType("image/png");
            }
            outputStream.write(data);
            outputStream.flush();
        } catch (IOException e) {
            log.error("图片logo读取失败");
            e.printStackTrace();
        }
    }

    /**
     * @Description 删除图片
     **/
    public static void deleteImage(String path, String name) {
        File image = new File(path + File.separator + name);
        if (image.exists()) {
            image.delete();
        }
        image = new File(getCompressImageName(path, name));
        if (image.exists()) {
            image.delete();
        }
    }

    /**
     * 删除文件
     * @param path
     * @param name
     */
    public static void deleteFile(String path, String name) {
        if (StringUtils.isBlank(name)) {
            return;
        }
        File file;
        if (path.lastIndexOf("/") == path.length() - 1) {
            file = new File(path + name);
        } else {
            file = new File(path + "/" + name);
        }
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 保存logo 先删除原先的，压缩图片
     */
    private String saveLogo(MultipartFile logoFile, String logo) {
        if (logoFile == null) {
            return null;
        }
        if (StringUtils.isNotEmpty(logo)) {
            FileUtil.deleteImage("/data/images/", logo);
        }
        File file = new File("/data/images/");
        if (!file.exists()) {
            file.mkdirs();
        }
        // 获取图片名称
        String picName = UUID.randomUUID().toString().replace("-", "");
        String fileType = StringUtils.substringAfterLast(logoFile.getOriginalFilename(), ".");
        String pictureName = picName + "." + fileType;
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(logoFile.getBytes());
             ByteArrayInputStream suitStream = new ByteArrayInputStream(logoFile.getBytes())) {
            Thumbnails.of(inputStream).scale(1d)
                    .outputQuality(0.25d)
                    .toFile(FileUtil.getCompressImageName("/data/images/", pictureName));
            Thumbnails.of(suitStream).scale(1d).outputQuality(1d)
                    .toFile("/data/images/" + File.separator + pictureName);
        } catch (IOException e) {
            log.error("save person image failed," + e.getMessage());
        }
        return pictureName;
    }

    /**
     * 保存文件
     * @param documentFile
     * @param documentUrl
     * @return
     */
    private String saveDocument(MultipartFile documentFile, String documentUrl) {
        if (null == documentFile) {
            return null;
        }
        if (StringUtils.isNotEmpty(documentUrl)) {
            FileUtil.deleteFile("/data/document/", documentUrl);
        }
        try {
            //documentFile.transferTo(new File("/data/document/test.txt"));
            String fileName = UUID.randomUUID().toString().replace("-", "");
            String fileType = StringUtils
                    .substringAfterLast(documentFile.getOriginalFilename(), ".");
            fileName = fileName + "." + fileType;
            FileUtil.saveFile("/data/document/", fileName, documentFile.getInputStream());
            return fileName;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


    public static String getCompressImageName(String savePath, String imageName) {
        StringBuffer sb = new StringBuffer(savePath);
        sb.append(File.separator).append(imageName, 0, imageName.indexOf(".")).append("_compress")
            .append(imageName.substring(imageName.indexOf(".")));
        return sb.toString();
    }

    public static void downloadFile(byte[] message, OutputStream out) {
        if (message == null || message.length == 0) {
            return;
        }
        try (ByteArrayInputStream in = new ByteArrayInputStream(message)) {
            byte[] bytes = new byte[2048];
            int length;
            while ((length = in.read(bytes)) != -1) {
                out.write(bytes, 0, length);
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("下载文件异常", e);
        }
    }

    public static byte[] readFile(String path, String name) {
        File file = new File(path + File.separator + name);
        if (!file.exists()) {
            log.info("文件不存在,{}", name);
            return null;
        }
        try (BufferedInputStream in = new BufferedInputStream(
            new FileInputStream(file)); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] bytes = new byte[2048];
            int length;
            while ((length = in.read(bytes)) != -1) {
                out.write(bytes, 0, length);
            }
            out.flush();
            return out.toByteArray();
        } catch (IOException e) {
            log.error("下载文件异常", e);
        }
        return null;
    }

    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            log.info("创建目录" + destDirName + "失败，目标目录已经存在");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        //创建目录
        if (dir.mkdirs()) {
            log.info("创建目录" + destDirName + "成功！");
            return true;
        } else {
            log.info("创建目录" + destDirName + "失败！");
            return false;
        }
    }

}
